angular.module('projectList', ['ui.grid', 'ui.grid.selection', 'ui.select', 'ui.grid.pagination',
    'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'toastr', 'common'])
    .controller('projectListController',
    ['$scope', '$http', 'toastr','commonService',
        function ($scope, $http, toastr,commonService) {
            $scope.filter = {
                name: '',
                status: '',
                start_date: {
                    from: null,
                    to: null
                },
                page: 1,
                size: 10
            };
            var role = $("#myRole").val();

            if (!!$.cookie("toast")) {
                toastr.success($.cookie("toast"));
                $.cookie("toast", "");
            }

            $scope.option = [];
            $scope.optionNoAll = [];
            $http.get('/user/mapping').success(function(data){
                $scope.option.push({id:"",value:"全部"});
                [].push.apply($scope.option,data.statusKey);
                [].push.apply($scope.optionNoAll,data.statusKey);
            });

            $scope.data = [];

            var nameTpl;
            nameTpl = '<span class="grid-data">{{MODEL_COL_FIELD}}</span>';
            $scope.columnOptions = [
                {
                    field: "un_id",
                    name: "项目编号",
                    enableColumnMenu: false,
                    width: 80,
                    cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                },
                {
                    field: "p_name",
                    name: "项目名称",
                    width: 350,
                    enableColumnMenu: false,
                    cellTemplate: nameTpl
                },
                {
                    field: "status",
                    name: "状态",
                    enableColumnMenu: false,
                    width: 150,
                    selectOptions: $scope.optionNoAll,
                    cellTemplate: '<ui-select ng-model="MODEL_COL_FIELD" on-select="col.colDef.onSelect(row)" append-to-body="true">' +
                    '<ui-select-match>{{ $select.selected.value }}</ui-select-match>' +
                    '<ui-select-choices repeat="item.id as item in col.colDef.selectOptions">' +
                    '<div>{{ item.value }}</div>' +
                    '</ui-select-choices>' +
                    '</ui-select>',
                    onSelect: function (row) {
                        row.dirty = true;
                    }
                },
                {
                    field: "project_pm",
                    name: "项目经理",
                    enableColumnMenu: false,
                    cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                },
                {
                    field: "project_leader",
                    name: "技术组长",
                    enableColumnMenu: false,
                    cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                },
                {
                    field: "start_date",
                    name: "开始时间",
                    enableColumnMenu: false,
                    cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                },
                {
                    field: "end_date",
                    name: "结束时间",
                    enableColumnMenu: false,
                    cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                }
            ];
            if (role === 'admin') {
                $scope.columnOptions.push({
                    field: "p_id",
                    name: "编辑",
                    enableColumnMenu: false,
                    width: "50",
                    cellTemplate: '<a class="grid-option" href="/project/update/{{MODEL_COL_FIELD}}">' +
                    '<i class="fa fa-lg fa-edit"></i></a>'
                });
                $scope.columnOptions.push({
                    field: "p_id",
                    name: "保存",
                    enableColumnMenu: false,
                    width: "50",
                    cellTemplate: '<a class="grid-option" href="javascript:void(0)" ng-click="col.colDef.saveChange(row)">' +
                    '<i class="fa fa-lg fa-save" style="color :#d50"></i></a>',
                    saveChange: function (row) {
                        if (row.dirty) {
                            row.dirty = false;
                            $http.post('/project/save', {
                                status: row.entity.status,
                                id: row.entity.p_id
                            }).success(function (data) {
                                if (data === 'success') {
                                    toastr.success('保存成功');
                                } else {
                                    toastr.error(data.description);
                                }
                            }).error(function () {
                                toastr.error('请检查网络连接');
                            });
                        } else {
                            toastr.warning('未做任何改动');
                        }
                    }
                });
            }
            $scope.gridOption = {
                enableVerticalScrollbar: 0,
                enableColumnResizing: true,
                enableSelectAll: true,
                exporterOlderExcelCompatibility: true,
                enablePaging: true,
                paginationPageSizes: [10, 25, 50],
                paginationPageSize: 10,
                useExternalPagination: true,
                paginationTemplate: '/views/gridPagination.html',
                enableGridMenu: false,
                enableRowSelection: true,
                excessRows: 1000,
                columnDefs: $scope.columnOptions,
                data: $scope.data
            };

            $scope.gridOption.onRegisterApi = function (gridApi) {
                $scope.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    $scope.filter.page = newPage;
                    $scope.filter.size = pageSize;
                    $scope.gridOption.paginationPageSize = pageSize;
                    queryData();
                });
            };

            $scope.addProject = function () {
                //window.location.href = '/project/add';
                $(".modal-add").css('display','block');
                $("#modal-c").css('z-index','1000');
                $("#modal-i").css('z-index','1000');
            };

            $scope.importExcel = function(){
                $(".batch-import").modal();
            };

            $scope.deleteProject = function () {
                if ($scope.gridApi.selection.getSelectedRows().length > 0) {
                    var deleteRows = [];
                    $scope.gridApi.selection.getSelectedRows().forEach(function (e) {
                        deleteRows.push(e.p_id);
                    });
                    $(".remove-prj").modal();
                    $("#ensure-remove").on("click", function () {
                        $(".remove-prj").modal('hide');
                        $http.post('/project/delete', {id: deleteRows}).success(function (result) {
                            if (result == "success") {
                                queryData();
                                toastr.success("批量删除成功!");
                            } else {
                                toastr.error("删除失败!" + result.description);
                            }
                        }).error(function () {
                                toastr.error("请检查网络连接");
                            }
                        );
                    });
                } else {
                    toastr.warning("未选择任何一行");
                }
            };

            $scope.reset = function () {
                $scope.filter = {
                    name: '',
                    status: '',
                    start_date: {
                        from: null,
                        to: null
                    },
                    page : 1,
                    size : 10
                };
                $("#date-timepicker").val('');
                $("#date-timepicker2").val('');
                queryData();
            };

            $("#timepicker").click(function () {
                $("#date-timepicker").val('');
                $scope.filter.start_date.from = null;
            });
            $("#timepicker2").click(function () {
                $("#date-timepicker2").val('');
                $scope.filter.start_date.to = null;
            });

            $scope.search = function () {
                queryData();
            };

            function queryData() {
                $scope.filter.limit = ($scope.filter.page - 1) * $scope.filter.size;
                $scope.filter.count = $scope.filter.limit + $scope.filter.size;
                $http.post('/project/find', $scope.filter).success(function (data) {
                    var un_id = 0;
                    data.data.forEach(function (e) {
                        e.un_id = ++un_id + ($scope.filter.page-1) * $scope.filter.size;
                    });
                    $scope.gridOption.data = data.data;
                    $scope.gridOption.totalItems = data.total;
                    setTimeout(function(){
                        $(window).resize();
                    },100);
                    if (data.data.length == 0) {
                        toastr.success("未查询到数据!");
                    }
                }).error(function () {
                    toastr.error("请检查网络连接");
                });
            }

            $("#from").datetimepicker();
            $("#to").datetimepicker();
            queryData();

            window.uploadFile = function(upload){
                if(/.*\.xlsx$/.test($("input[type='file']").val())){
                    $("#fileReplace").val($("#file").val());
                    if(!!upload) {
                        $("#fileReplace").val("");
                        $.ajaxFileUpload({
                            url: '/project/upload',
                            type: 'post',
                            secureuri: false,
                            fileElementId: 'file',
                            dataType: 'text',
                            success: function(data){
                                if(data == 'success') {
                                    $(".batch-import").modal("hide");
                                    $.cookie("toast","批量导入成功");
                                    window.location.href = window.location.href;
                                } else {
                                    toastr.error("导入失败!" + data);
                                }
                            },
                            error: function(data, status, e){
                                toastr.error("请检查网络连接")
                            }
                        });
                    }
                } else{
                    toastr.warning("请选择Excel表格文件类型");
                }
            }

        }
    ]);